<template>
    <!-- <a-icon type="edit" class="editable-cell-icon" @click="showModal" /> -->
    <drag-modal v-model="visible" title="公式" on-ok="handleOk" @cancel="handleCancel" width="900px">
        <!-- 按钮 -->
        <a-row class="text-center clearfix " style="margin-bottom:10px; border-bottom: 1px solid #ddd;padding-bottom: 5px;cursor:pointer;">
            <a-col :xs="25" :sm="25" :md="25" :lg="16" :xl="12">
                <!-- v-show="design" -->

                <a-radio-group v-model="radiovalue" @change="countclick">
                    <a-radio :value="1">
                        取值
                    </a-radio>
                    <a-radio :value="2">
                        公式
                    </a-radio>
                </a-radio-group>
            </a-col>
        </a-row>

        <div class="stalxa" v-if="counttype">
            <span class="ohp js-top">科目：</span>
            <a-tree-select v-model="subject" show-search style="width: 30%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="选择科目" allow-clear tree-default-expand-all>
                <a-tree-select-node v-for="(item,id) in dropdown" :value="item.name" :title="item.name" :key="item.id+item.name">
                </a-tree-select-node>
            </a-tree-select>
            <span class="ohp js-top">取数规则：</span>
            <span class="ohp">
                <a-select :default-value="dropdown[0]" style="width: 120px" v-model="number">
                    <a-select-option v-for="province in FormulaList" :key="province">
                        {{ province }}
                    </a-select-option>
                </a-select>
            </span>
            <span class="ohp js-top">运算符：</span>
            <span class="js-top">
                <a-radio-group name="radioGroup" v-model="operator">
                    <a-radio :value="1">
                        +
                    </a-radio>
                    <a-radio :value="2">
                        -
                    </a-radio>
                </a-radio-group>
            </span>
            <span class="ohp">
                <a-button type="primary" @click="handleAdd">
                    添加
                </a-button>
            </span>
        </div>
        <div v-if="counttype">
            <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false" style="min-height: 200px">
                <template slot="operation" slot-scope="text, record">
                    <a-popconfirm v-if="dataSource.length" title="是否删除?" @confirm="() => onDelete(record.key)">
                        <a href="javascript:;">删除</a>
                    </a-popconfirm>
                </template>
            </a-table>
        </div>
        <!-- <div v-if="!counttype">
            运算符号：
            <a-tag @click="searchChlick(1)">+</a-tag>
            <a-tag @click="searchChlick(2)">-</a-tag>
        </div> -->
        <div v-if="!counttype">
            <div class="valuelist">
                <div class="valuelsit-title">
                    {{thisTilte}}
                </div>
                <div class="valuelist-list">
                    <a-input v-model="inpvalue" @change="intClick" />
                </div>
            </div>
            <table border="1" class="table-style">
                <tr v-for="(item,index) in listNumber" v-if="index >= 4">
                    <td @click="listCLick(item.Ctype,item,'Ctype','C')">C{{item}}</td>
                    <td @click="listCLick(item.Dtype,item,'Dtype','D')">D{{item}}</td>
                    <td @click="listCLick(item.Gtype,item,'Gtype','G')">G{{item}}</td>
                    <td @click="listCLick(item.Htype,item,'Htype','H')">H{{item}}</td>
                </tr>
            </table>
        </div>
        <template slot="footer">
            <a-button key="back" @click="handleCancel">
                关闭
            </a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
                保存
            </a-button>
        </template>
    </drag-modal>

</template>
<script>

import { save, getFormulaList, getAccountingLedgers, saveFormula, getAssetsLiabilities } from '@/api/finance/liablities/liablitieslist'

export default {
    props: {
        stalid: Number,
        col: {
            String,
            default: ''
        },
        doindex: {
            Number,
            default: ''
        },
        uid: {
            Number,
            default: ''
        },
        listNumber: {
            Number,
            default: ''
        }
    },
    data () {
        return {
            counttype: true,  // 公式，计算切换
            treeExpandedKeys: [], // 获取公式列表
            value: undefined,
            loading: false,
            visible: false,
            radiovalue: 1,
            // 默认列表数据
            dataSource: [],// 公式列表显示
            dataSourcelist: [],
            count: 2,
            // 列表标题
            columns: [
                {
                    title: '科目',
                    dataIndex: 'subject',
                    width: '30%',
                    scopedSlots: { customRender: 'subject' },
                },
                {
                    title: '预算符',
                    dataIndex: 'tap',
                },
                {
                    title: '取数规则',
                    dataIndex: 'number',
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    scopedSlots: { customRender: 'operation' },
                },
            ],
            // 列表标题
            columna: [
                {
                    title: 'C',
                    dataIndex: 'C',
                    width: '30%',
                    scopedSlots: { customRender: 'C' },
                },
                {
                    title: 'D',
                    dataIndex: 'D',
                    scopedSlots: { customRender: 'D' },
                },
                {
                    title: 'G',
                    dataIndex: 'G',
                    scopedSlots: { customRender: 'G' },
                },
                {
                    title: 'H',
                    dataIndex: 'H',
                    scopedSlots: { customRender: 'H' },
                },
            ],
            selectedItems: [],
            // 下拉菜单科目
            dropdown: [],
            // 下拉公式列表
            FormulaList: [
                '余额', '本级借方余额', '本级贷方余额', '末级借方余额', '末级贷方余额'
            ],
            topLists: ['C', 'D', 'G', 'H'],    //表头领标

            subject: '',
            number: '',
            operator: 1,
            tap: '',
            accessRule: '',
            runData: [],
            davabses: [],
            stalsname: [],
            oid: '',
            setkey: '',
            datalist: [],
            roaarray: [],

            Symbol: '',  // 用户输入运算符

            strtype: 1,

            oldData: [],

            thisTilte: '',

            vtypes: true,

            inpvalue: '',

            strType: 0, // 回显支付窜状态

            jsstr: '',
        };
    },
    created () {
        // this.Ledgers();
        // this.laList();
        this.inputValues();
        console.log('-----------行', this.listNumber);

    },
    computed: {
        filteredOptions () {
            return OPTIONS.filter(o => !this.selectedItems.includes(o));
        },

    },
    methods: {

        intClick (vals) {
            if (this.inpvalue == '') {
                this.strtype = 1;
            } else {

                if (this.inpvalue.substring(this.inpvalue.length - 1) != '-' || this.inpvalue.substring(this.inpvalue.length - 1) != '+') {
                    this.inpvalue = vals.target.value;
                    this.strType = 0;
                    this.Symbol = '';
                }
                if (this.inpvalue.substring(this.inpvalue.length - 1) == '-') {
                    this.Symbol = '-';
                    this.strType = 0;
                    this.jsstr = this.Symbol;
                }
                if (this.inpvalue.substring(this.inpvalue.length - 1) == '+') {
                    this.Symbol = '+';
                    this.strType = 0;
                    this.jsstr = this.Symbol;
                }
            }
        },

        // 初始化input 数据
        inputValues () {
            this.thisTilte = this.distinguish(this.col) + (this.doindex + 1) + '=';
        },
        // 单元格选中 
        listCLick (val, key, code, liestr) {
            if (this.strType == 1) {
                this.$message.warning('请先输入运算符');
                return;
            }
            let stastr = '';
            if (this.strtype == 1) {
                this.inpvalue = liestr + (key);
                this.strtype++;
            } else {
                if (this.Symbol) {
                    this.inpvalue = this.inpvalue + liestr + (key);
                    this.jsstr = this.Symbol;
                    this.Symbol = '';
                } else {
                    if (!this.jsstr) {
                        this.inpvalue = liestr + (key);
                    } else {
                        this.inpvalue = this.inpvalue.substr(0, this.inpvalue.length - this.inpvalue.split(this.jsstr)[this.inpvalue.split(this.jsstr).length - 1].length) + liestr + (key)
                    }
                }
            }
        },

        // 选取 计算或公式雀环
        countclick (val) {
            if (val.target.value == 1) {
                this.counttype = true;
            }
            if (val.target.value == 2) {
                this.counttype = false;
                this.postHttp();
            }
        },

        // 显示弹窗列表
        showModal () {
            this.visible = true;
            this.Ledgers();
            this.laList();
        },

        // 关闭弹窗列表
        handleCancel (e) {
            this.visible = false;
        },

        handleChange (selectedItems) {
            this.selectedItems = selectedItems;
        },

        // 获取列表参数
        onCellChange (key, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find(item => item.key === key);
        },

        // 列表删除
        onDelete (key) {
            const dataSource = [...this.dataSource];
            this.dataSource = dataSource.filter(item => item.key !== key);
        },

        // 获取科目列表
        Ledgers () {
            getAccountingLedgers().then((rst) => {
                for (var i = 0; i < rst.data.length; i++) {
                    this.stalsname[i] = rst.data[i];
                    const data = { 'name': rst.data[i].name, 'id': rst.data[i].id }
                    this.dropdown.push(data);
                }
            })
        },

        // 获取公式列表
        laList () {
            getFormulaList({ 'alId': this.uid }).then((row) => {
                console.log('公式列表', row)
                let cont = 1;
                this.dataSource = [];
                this.datalist = row.data;
                for (let i = 0; i < row.data.length; i++) {
                    this.dataSource.push({
                        key: cont,
                        accountingId: row.data[i].accountingId,
                        accessRule: row.data[i].accessRule,
                        operator: row.data[i].operator,
                        // id: row.data[i].id,
                        subject: row.data[i].accountingName,
                        tap: row.data[i].operator == 1 ? '+' : '-',
                        number: row.data[i].accessRule == 1
                            ? '余额' : row.data[i].accessRule == 2
                                ? '本级借方余额' : row.data[i].accessRule == 3
                                    ? '本级贷方余额' : row.data[i].accessRule == 4
                                        ? '末级借方余额' : row.data[i].accessRule == 5
                                            ? '末级贷方余额' : '未选择'
                        ,
                    })
                    cont++;
                    this.setkey = cont;
                }
            })

        },

        // 列表添加
        handleAdd () {
            const { count, dataSource } = this;
            this.runData = [];
            if (this.subject === '') {
                this.$message.warning('请选择科目');
                return;
            }
            if (this.number === '') {
                this.$message.warning('请选择规则');
                return;
            }
            if (this.operator == 1) {
                this.tap = "+"
            } else if (this.operator) {
                this.tap = "-"
            }
            if (this.number == '余额') {
                this.accessRule = 1;
            }
            if (this.number == '本级借方余额') {
                this.accessRule = 2;
            }
            if (this.number == '本级贷方余额') {
                this.accessRule = 3;
            }
            if (this.number == '末级借方余额') {
                this.accessRule = 4;
            }
            if (this.number == '末级贷方余额') {
                this.accessRule = 5;
            }
            for (let jk = 0; jk < this.stalsname.length; jk++) {
                if (this.stalsname[jk].name == this.subject) {
                    this.oid = this.stalsname[jk].id
                }
            }
            const newData = {
                key: this.setkey++,
                subject: this.subject,
                tap: this.tap,
                accountingName: this.subject,
                number: this.number,
                accessRule: this.accessRule,
                uosname: this.subject,
            };
            this.dataSource = [...dataSource, newData];
            console.log(this.dataSource)
        },

        // 列表保存 
        handleOk () {
            if (this.counttype) {
                let rows = '';
                let data = [];
                this.runData = [];
                this.davabses = [];
                if (this.datalist.length == 0) {
                    for (let i = 0; i < this.dataSource.length; i++) { // 新增数据构造
                        if (this.dataSource[i].tap == "+") {
                            rows = 1;
                        } else if (this.dataSource[i].tap == "-") {
                            rows = 2;
                        }
                        this.runData.push({
                            'id': this.dataSource[i].id,
                            'accessRule': this.dataSource[i].accessRule,
                            'accountingId': this.oid,
                            'accountingName': this.dataSource[i].subject,
                            'operator': rows,
                            'alId': this.uid,
                            'type': 1,
                            'col': this.col,
                            'doindex': this.doindex
                        })
                    }
                    for (let k = 0; k < this.runData.length; k++) {
                        console.log(this.runData)
                        if (this.runData[k]['col'] == 'FinaltermOne') {
                            data = this.runData;
                        }
                        if (this.runData[k]['col'] == 'FinaltermTow') {
                            data = this.runData;
                        }
                        if (this.runData[k]['col'] == 'BeginningOne') {
                            data = this.runData;
                        }
                        if (this.runData[k]['col'] == 'BeginningTow') {
                            data = this.runData;
                        }
                    }
                    this.davabses.push(data);
                    this.$emit('childByValue', this.davabses);
                    setTimeout(() => {
                        this.$message.success(`保存成功`);
                        this.$emit('closeModal');
                        this.visible = false;
                    }, 500);

                } else {
                    this.runData = [];
                    for (let i = 0; i < this.dataSource.length; i++) { // 新增数据构造
                        if (this.dataSource[i].tap == "+") {
                            rows = 1;
                        } else if (this.dataSource[i].tap == "-") {
                            rows = 2;
                        }
                        this.runData.push({
                            'accessRule': this.dataSource[i].accessRule,
                            'accountingId': this.oid,
                            'id': this.dataSource[i].id,
                            'accountingName': this.dataSource[i].subject,
                            'operator': rows,
                            'type': 2,
                            'uid': this.stalid,
                            'col': this.col,
                            'doindex': this.doindex
                        })
                    }
                    for (let k = 0; k < this.runData.length; k++) {
                        if (this.runData[k]['col'] == 'FinaltermOne') {
                            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
                        }
                        if (this.runData[k]['col'] == 'FinaltermTow') {
                            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
                        }
                        if (this.runData[k]['col'] == 'BeginningOne') {
                            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
                        }
                        if (this.runData[k]['col'] == 'BeginningTow') {
                            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
                        }
                    }
                    this.davabses.push(data);
                    console.log('this is complete databases', this.davabses)
                    saveFormula(this.davabses).then((rst) => {
                        if (rst.code == 200) {
                            setTimeout(() => {
                                this.$message.success(`保存成功`);
                                this.visible = false;
                            }, 500);
                        }
                    })
                }
            } else {
                const data = {
                    'id': this.uid,
                    'accountYear': new Date().getFullYear(),
                    // 'value': this.inpvalue,
                    'formula': this.inpvalue,
                    'columns': this.distinguish(this.col),
                    'line': Number(this.doindex) + 1,
                    // 'assetsLiabilitiesFormulas': '',
                    'type': 1,
                    'valueType': 3
                };
                this.oldData.push(data);
                console.log(this.oldData)
                // 初始化选中第一格
                this.strtype = 1;
                // 初始化输入运算符号
                this.Symbol = '';
                this.inputValues();
                save(this.oldData).then(rows => {
                    if (rows.code == 200) {
                        setTimeout(() => {
                            this.$message.success(`保存成功`);
                            this.visible = false;
                            this.$emit('calculation', 1);
                        }, 500);
                    }
                })
            }
        },

        distinguish (list) {
            if (list == 'FinaltermOne') {
                return 'C'
            }
            if (list == 'BeginningOne') {
                return 'D'
            }
            if (list == 'FinaltermTow') {
                return 'G'
            }
            if (list == 'BeginningTow') {
                return 'H'
            }
        },

        // 回显表格
        postHttp () {


            let _this = this;
            _this.dataSourcelist = [];
            let List = ['C', 'D', 'G', 'H'];
            let databases = { 'accountPeriod': "0", 'type': 1 }; //默认时间
            getAssetsLiabilities(databases).then((rst) => {
                if (rst.code == 200 && rst.data) {
                    this.oldData = rst.data;    // 初始化提交数据 
                    let maxNumber = rst.data[0].line;
                    let strlength = 0;
                    for (let index = 0; index < rst.data.length; index++) {
                        // if (rst.data[index].columns == "A" && rst.data[index].type == 1) {
                        //     strlength++;
                        // }

                        if (maxNumber < rst.data[index].line) {
                            maxNumber = rst.data[index].line;
                        }
                    }

                    strlength = maxNumber;
                    for (let j = 4; j <= strlength; j++) {
                        let item = {};
                        for (let i = 0; i < rst.data.length; i++) { // 数据循环
                            if (rst.data[i].type == 1) {
                                for (let k = 0; k <= this.topLists.length; k++) {  // 表头循环，拼接数据
                                    if (rst.data[i].line == j && rst.data[i].columns == this.topLists[k] && rst.data[i].valueType != 2) {
                                        if (rst.data[i].value) {
                                            item[List[k]] = rst.data[i].line;
                                            item[List[k] + 'type'] = false;
                                            item[List[k] + 'code'] = rst.data[i].columns;
                                            item[List[k] + 'value'] = rst.data[i].value;
                                        }
                                    }
                                }
                            }
                        }
                        this.dataSourcelist.push(item);
                    }

                    // 初始化公式
                    rst.data.forEach(item => {
                        if (item.id == this.uid && item.formula) {
                            this.inpvalue = item.formula;
                            this.strtype = 2;
                            this.strType = 1;
                        }
                    })
                }
            })
        },
    },
};
</script>
<style lang="less" scoped>
    .valuelist {
        display: flex;
        height: 60px;
        line-height: 60px;

        .valuelsit-title {
            width: 5%;
            text-align: center;
        }

        .valuelist-list {
            width: 80%;
        }
    }

    .input-list {
        display: flex;
        margin-bottom: 10px;
        width: 100%;
        input {
            width: 60px;
        }
    }
    .tabelist {
        display: flex;
        justify-content: space-between;
        width: 100%;
        border: 1px solid red;
    }
    .table-list {
        border: 1px solid red;
        height: 30px;
        line-height: 30px;
    }

    .table-style {
        width: 100%;
        border: 1px solid #cacaca;
        text-align: center;
    }
    .table-title {
        text-align: center;
        background: #eeeeee;
    }

    .button-list {
        border: 1px solid red;
        display: flex;
        text-align: center;
        .button-box {
            width: 70px;
            height: 60px;
            line-height: 60px;
            border: 1px solid red;
        }
    }
    .tou:hover {
        color: #2d55d8;
    }

    .imgcolor {
        color: #1890ff;
    }

    .ohp {
        margin-left: 20px;
    }

    .stalxa {
        display: flex;
        margin: 0 0 10px 0;
    }

    .js-top {
        margin-top: 5px;
    }

    .editable-cell {
        position: relative;
    }

    .editable-cell-input-wrapper,
    .editable-cell-text-wrapper {
        padding-right: 24px;
    }

    .editable-cell-text-wrapper {
        padding: 5px 24px 5px 5px;
    }

    .editable-cell-icon,
    .editable-cell-icon-check {
        position: absolute;
        right: 0;
        width: 20px;
        cursor: pointer;
    }

    .editable-cell-icon {
        line-height: 18px;
        display: none;
    }

    .editable-cell-icon-check {
        line-height: 28px;
    }

    .editable-cell:hover .editable-cell-icon {
        display: inline-block;
    }

    .editable-cell-icon:hover,
    .editable-cell-icon-check:hover {
        color: #108ee9;
    }

    .editable-add-btn {
        margin-bottom: 8px;
    }
</style>